<?php

namespace App\Http\Controllers\Admin\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StudentResultRequest;
use App\Models\Examination;
use App\Models\StudentResult;
use App\Models\UserHasSection;
use App\Services\Result\ResultInterface;
use App\Transformers\Admin\StudentResultTransformer;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class StudentResultController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $data = Examination::query()
            ->select('id', 'name', 'category_id', 'type', 'start_time', 'over_time', 'timer', 'peoples')
            ->pimp()
            ->get();

        return $this->response->collection($data, new StudentResultTransformer())->addMeta('category', cacheTextBank());
    }

    /**
     * @param StudentResultRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function store(StudentResultRequest $request)
    {


        // 提交试卷的用户
        $request->offsetSet('user_id', auth()->id());
        $request->offsetSet('name', auth()->user()->name);
        $request->offsetSet('username', auth()->user()->username);

        // 用户所属的部门
        $userSection = UserHasSection::query()
            ->select('section_id')
            ->where('user_id', $request->input('user_id'))
            ->get();

        // 获取id数组 拼接字符串
        $ids = collect($userSection)->pluck('section_id');
        $userSection = ',';
        foreach ($ids as $v) {
            $userSection .= $v . ',';
        }

        $request->offsetSet('userSectionIds', $userSection);

        // 错误题目数量
        $request->offsetSet('error_num', $request->input('all_num') - $request->input('success_num'));

        StudentResult::create($request->all());

        return $this->response->created();
    }

    /**
     * Display the specified resource.
     *
     * @param Examination $testResult
     * @param Request $request
     * @return Response
     */
    public function show(Examination $testResult, Request $request)
    {
        $namespace = 'App\\Services\\Result\\Type\\' . ucfirst($request->input('type')) . 'Result';

        // 判断类名是否存在
        if (!class_exists($namespace)) {
            return $this->response->errorNotFound($namespace . '未定义');
        }

        // 解析类
        $class = resolve($namespace);

        // 判断类是否实现QuestionInterface的接口
        if (!$class instanceof ResultInterface) {
            return $this->response->errorNotFound('ResultInterface未实现');
        }

        $data = $class->show($testResult, $request);

        return $this->response->array(['data' => $data]);
    }
}
